﻿namespace Manhua3.Helper
{
    using Manhua3.Client;
    using Manhua3.Common;
    using System;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;
    using Windows.Data.Xml.Dom;
    using Windows.Foundation;
    using Windows.Storage;
    using Windows.UI.Notifications;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Media;

    public class MethodHelper
    {
        /// <summary>
        /// 创建并显示Toast通知
        /// </summary>
        /// <param name="bodytext">正文内容</param>
        /// <param name="title">标题(可选参数)</param>
        /// <param name="image">
        /// 图片(可选参数)
        /// http:// 基于Web的图像。
        /// ms-appx:/// 应用包中包含的图像。
        /// ms-appdata:///local/ 保存到本地存储中的图像。
        /// </param>
        /// <param name="alt">图片指示内容(可选)</param>
        /// <param name="duration">Toast持续时间</param>
        /// <param name="audio">
        /// Toast音频(可选)
        /// ms-winsoundevent 前缀， 例如 ms-winsoundevent:Notification.Mail
        /// 非循环播放声音
        /// Notification.Default
        /// Notification.IM
        /// Notification.Mail
        /// Notification.Reminder
        /// Notification.SMS
        /// 循环播放声音
        /// Notification.Looping.Alarm
        /// Notification.Looping.Alarm2
        /// Notification.Looping.Call
        /// Notification.Looping.Call2
        /// </param>
        /// <param name="loop"></param>
        /// <returns></returns>
        public static ToastNotifier ShowToast(
            string bodytext,
            string title = null,
            string image = null,
            string alt = null,
            string duration = "short",
            string audio = null,
            bool loop = false)
        {
            ToastTemplateType template;

            if (string.IsNullOrEmpty(image))
            {
                template = string.IsNullOrEmpty(title) ?
                            ToastTemplateType.ToastText01 :
                            ToastTemplateType.ToastText02;
            }
            else
            {
                template = string.IsNullOrEmpty(title) ?
                            ToastTemplateType.ToastImageAndText01 :
                            ToastTemplateType.ToastImageAndText02;
            }

            var xml = ToastNotificationManager.GetTemplateContent(template);
            var textElements = xml.GetElementsByTagName("text");
            var imageElements = xml.GetElementsByTagName("image");

            switch (template)
            {
                case ToastTemplateType.ToastImageAndText01:
                    ((XmlElement)imageElements[0]).SetAttribute("src", image);
                    if (!string.IsNullOrEmpty(alt))
                        ((XmlElement)imageElements[0]).SetAttribute("alt", alt);
                    textElements[0].InnerText = bodytext;
                    break;

                case ToastTemplateType.ToastImageAndText02:
                    ((XmlElement)imageElements[0]).SetAttribute("src", image);
                    if (!string.IsNullOrEmpty(alt))
                        ((XmlElement)imageElements[0]).SetAttribute("alt", alt);
                    textElements[0].InnerText = title;
                    textElements[1].InnerText = bodytext;
                    break;

                case ToastTemplateType.ToastText01:
                    textElements[0].InnerText = bodytext;
                    break;

                case ToastTemplateType.ToastText02:
                    textElements[0].InnerText = title;
                    textElements[1].InnerText = bodytext;
                    break;
            }

            var boot = ((XmlElement)xml.SelectSingleNode("/toast"));
            boot.SetAttribute("duration", duration);

            if (!string.IsNullOrEmpty(audio))
            {
                var audioElement = xml.CreateElement("audio");
                audioElement.SetAttribute("src", audio);
                audioElement.SetAttribute("loop", loop ? "true" : "false");
                boot.AppendChild(audioElement);
            }

            var tn = new ToastNotification(xml);
            var notifier = ToastNotificationManager.CreateToastNotifier();
            notifier.Show(tn);
            return notifier;
        }

        private static async Task<bool> IsExists(StorageFolder folder, string filename)
        {
            bool exists = true;

            try
            {
                var t = await folder.GetFileAsync(filename);
                if ((await t.GetBasicPropertiesAsync()).Size == 0)
                    exists = false;
            }
            catch
            {
                exists = false;
            }

            return exists;
        }

        public static Task<bool> FileIsExists(string filename)
        {
            return IsExists(Windows.Storage.ApplicationData.Current.LocalFolder, filename);
        }

        public static Task<bool> TempFileIsExists(string filename)
        {
            return IsExists(Windows.Storage.ApplicationData.Current.TemporaryFolder, filename);
        }

        public static IAsyncOperation<StorageFile> LoadFileFromInstall(string filename)
        {
            return Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filename);
        }

        /// <summary>
        /// 下载文件并保存到temp文件夹
        /// </summary>
        /// <param name="url"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static async Task<bool> DownloadFile(string url, string name)
        {
            try
            {
                HttpWebRequest request = HttpWebRequest.CreateHttp(url);
                var response = await request.GetResponseAsync();

                var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder
                                  .CreateFileAsync(name);

                using (var ms = await file.OpenStreamForWriteAsync())
                using (Stream stream = response.GetResponseStream())
                {
                    await stream.CopyToAsync(ms, 4096);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static Task<IUICommand> ShowMessageDialog(string msg, string title = null)
        {
            if (title == null) title = Global.DefaultDialogTitle;
            MessageDialog dialog = new MessageDialog(msg, title);
            return dialog.ShowAsync().AsTask();
        }

        public static Task<IUICommand> ShowMessageDialogNotEmpty(string msg, string title = null)
        {
            if (string.IsNullOrEmpty(msg))
                return Task.Factory.StartNew(new Func<IUICommand>(() => { return null; }));

            return ShowMessageDialog(msg, title);
        }

        public static T SearchVisualTree<T>(DependencyObject elem) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(elem);
            if (count == 0)
                return null;

            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(elem, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    var res = SearchVisualTree<T>(child);
                    if (res != null)
                    {
                        return res;
                    }
                }
            }

            return null;
        }
    }
}
